package ru.mcfr.oxygen.updater.installer;

import org.apache.log4j.Logger;
import ru.mcfr.oxygen.updater.Version;
import ru.mcfr.oxygen.updater.utils.Zipper;

import java.io.*;
import java.net.URLDecoder;

/**
 * Created by IntelliJ IDEA.
 * User: ws
 * Date: 28.04.11
 * Time: 18:01
 * To change this template use File | Settings | File Templates.
 */
public abstract class AbstractInstaller {

    protected Logger logger = Logger.getLogger(AbstractInstaller.class);
    protected String main_dir = "";
    protected boolean without_path = false;
    protected boolean disabled = false;

    public AbstractInstaller(String path){
        if (path.isEmpty())
            this.without_path = true;
        else if (new File(path).exists()){
            try {
                this.main_dir = URLDecoder.decode(path, "UTF8");
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException("Unable decode path to UTF8");
            }
        } else
            throw new IllegalStateException("Incorrect sources path!");
    }

    protected boolean if_disabled_message(){
        if (this.disabled)
            logger.error("Can't perform operation because this installer is disabled");
        return this.disabled;
    }

    public boolean savePreVersion(String storage, boolean needToZip){
        Version ver = Version.fromDir(main_dir);
        storage += ver.toString();
        if (needToZip){
            Zipper.zip(new File(main_dir), storage + ".zip");
        } else {
            (new File(main_dir)).renameTo(new File(storage));//replace with file copy method
        }
        return true;
    }

    protected abstract boolean install(String src);

    public boolean doInstallation(String src){
        if (!if_disabled_message())
            return install(src);
        return false;
    }
}
